//
//  MyselfViewController.m
//  MarianasTrench
//
//  Created by wangjue on 16/3/17.
//  Copyright © 2016年 王爵. All rights reserved.
//

#import "MyselfViewController.h"

const CGFloat BackHeight = 180;

@interface MyselfViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, RegisterViewControllerDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *imageBG;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) NSMutableArray *dataSource;
@property (nonatomic, retain) UIView *backView;
@property (nonatomic, retain) UIImageView *smallImage;
@property (nonatomic, retain) UILabel *smallLabel;

@end

@implementation MyselfViewController


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"登陆" style:UIBarButtonItemStylePlain target:self action:@selector(itemAction:)];
    self.navigationItem.leftBarButtonItem = item;
    
    
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"注销" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemAction:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.navigationItem.title = @"我的";
    
    self.tableView =[[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.contentInset = UIEdgeInsetsMake(BackHeight, 0, 0, 0);
    [self.view addSubview:_tableView];
    
    //设置搭的图片
    self.imageBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, -BackHeight, self.view.frame.size.width, BackHeight)];
    _imageBG.image = [UIImage imageNamed:@"0.jpeg"];
    [_tableView addSubview:_imageBG];
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, - 200, self.view.frame.size.width, 180)];
    [_tableView addSubview:_backView];
    
    self.smallImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 40, 90, 80, 80)];
    _smallImage.layer.masksToBounds = YES;
    _smallImage.layer.cornerRadius = 40;
    _smallImage.image = [UIImage imageNamed:@"c8177f3e6709c93d16cb6adb983df8dcd10054e4.jpg"];
    [_backView addSubview:_smallImage];
    
    self.smallLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, self.view.frame.size.width, 20)];
    //_smallLabel.backgroundColor = [UIColor redColor];
    _smallLabel.textAlignment = NSTextAlignmentCenter;
    _smallLabel.textColor = [UIColor grayColor];
    [_backView addSubview:_smallLabel];
    
    //获取当前用户
    BmobUser *bUser = [BmobUser getCurrentObject];
    if (bUser) {
        //进行操作
        _smallLabel.text = bUser.username;
    }else{
        //对象为空时，可打开用户注册界面
    }
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
  
}


//协议方法
-(void)userName:(NSString *)str{
    _smallLabel.text = str;
}

//登录
-(void)itemAction:(UIBarButtonItem *)item{
    RegisterViewController *VC = [[RegisterViewController alloc] init];
    VC.delegate = self;
    [self presentViewController:VC animated:YES completion:^{
        
    }];

}

//注销
-(void)rightItemAction:(UIBarButtonItem *)item{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注销提示" message:@"已经注销成功" preferredStyle:UIAlertControllerStyleAlert];
    
    
    
    UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [BmobUser logout];
        _smallLabel.text = nil;
    }];
    
    [alert addAction:alertAction1];
    [self presentViewController:alert animated:YES completion:nil];
    
    
    
    
}


#pragma mark - tableView Delegate &DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"清空播放历史";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-lishi"];
    }
    
    if (indexPath.row == 1) {
        cell.textLabel.text = @"清楚缓存";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-icon22"];
    }
    
    if (indexPath.row == 2) {
        cell.textLabel.text = @"关于我们";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-women"];
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        
        //创建搜索请求
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"History" inManagedObjectContext:[CoreDataManager shareManager].managedObjectContext];
        //设置搜索的实体
        [fetchRequest setEntity:entity];
        
        NSError *error = nil;
        //搜索返回数据
        NSArray *fetchedObjects = [[CoreDataManager shareManager].managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            NSLog(@"error : %@", error);
        }
        
        
        self.dataSource = [NSMutableArray arrayWithArray:fetchedObjects];
        if (_dataSource.count != 0) {
            
            for (History *history in _dataSource) {
                [[CoreDataManager shareManager].managedObjectContext deleteObject:history];
            }
            //History *history = _dataSource.firstObject;
            
            [[CoreDataManager shareManager]saveContext];
            

        }
        
               UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"清楚历史记录成功" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alert addAction:alertAction1];
        [self presentViewController:alert animated:YES completion:nil];
      }
    
    
    if (indexPath.row == 1) {
        //清除缓存
        NSString *path = [CacheClear getCachesPath];
        CGFloat pathImageCount = [CacheClear folderSizeAtPath:path];
        [CacheClear clearCache:path];
        
        NSString *countsStr = [NSString stringWithFormat:@"%.2fM", pathImageCount];
        NSString *str = [NSString stringWithFormat:@"成功清除全部缓存%@", countsStr];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清除缓存" message:str preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alert addAction:alertAction1];
        [self presentViewController:alert animated:YES completion:nil];
        

    }
    
    if (indexPath.row == 2) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"此版本为1.0版本" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alert addAction:alertAction1];
        [self presentViewController:alert animated:YES completion:nil];

    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset = scrollView.contentOffset.y;
    CGFloat xOffset = (yOffset + BackHeight) *2;
    if (yOffset < -BackHeight) {
        CGRect rect = _imageBG.frame;
        rect.origin.y = yOffset;
        rect.size.height = -yOffset;
        rect.origin.x = xOffset;
        rect.size.width = self.view.frame.size.width + fabs(xOffset) *2;
        _imageBG.frame = rect;
    }
    CGFloat alpha = (yOffset +BackHeight) / BackHeight;
    
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor whiteColor] colorWithAlphaComponent:alpha] ] forBarMetrics:UIBarMetricsDefault];
    
    
}

- (UIImage *)imageWithColor:(UIColor *)color{
    //描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    //开启为图上下文
    UIGraphicsBeginImageContext(rect.size);
    //获取位图的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    //渲染上下文
    CGContextFillRect(context, rect);
    //从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    //结束上下文
    UIGraphicsEndImageContext();
    return theImage;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
